import React, { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import io from 'socket.io-client';
import styles from './GroupChat.module.css';
import  {http,host,port} from '../utils/host'
const GroupChat = () => {
    const { groupId } = useParams();
    const navigate = useNavigate();
    const [messages, setMessages] = useState([]);
    const [newMessage, setNewMessage] = useState('');
    const [socket, setSocket] = useState(null);
    const [groupInfo, setGroupInfo] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState('');
    const [showEmojiPicker, setShowEmojiPicker] = useState(false);
    const [showGroupMenu, setShowGroupMenu] = useState(false);
    const [showInviteModal, setShowInviteModal] = useState(false);
    const [showRemoveModal, setShowRemoveModal] = useState(false);
    const [availableUsers, setAvailableUsers] = useState([]);
    const [selectedUsers, setSelectedUsers] = useState([]);
    const [selectedRemoveUser, setSelectedRemoveUser] = useState('');
    const [isLoading, setIsLoading] = useState(false);
    const messagesEndRef = useRef(null);
    
    // 表情数据
    const emojis = [
        '😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇',
        '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚',
        '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤩',
        '🥳', '😏', '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', '😣',
        '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠', '😡', '🤬',
        '🤯', '😳', '🥵', '🥶', '😱', '😨', '😰', '😥', '😓', '🤗',
        '🤔', '🤭', '🤫', '🤥', '😶', '😐', '😑', '😯', '😦', '😧',
        '😮', '😲', '🥱', '😴', '🤤', '😪', '😵', '🤐', '🥴', '🤢',
        '🤮', '🤧', '😷', '🤒', '🤕', '🤑', '🤠', '💩', '👻', '💀',
        '☠️', '👽', '👾', '🤖', '😺', '😸', '😹', '😻', '😼', '😽',
        '🙀', '😿', '😾', '🙈', '🙉', '🙊', '💌', '💘', '💝', '💖',
        '💗', '💓', '💞', '💕', '💟', '❣️', '💔', '❤️', '🧡', '💛',
        '💚', '💙', '💜', '🖤', '💯', '💢', '💥', '💫', '💦', '💨',
        '🕳️', '💬', '🗨️', '🗯️', '💭', '💤', '👋', '🤚', '🖐️', '✋',
        '🖖', '👌', '🤌', '🤏', '✌️', '🤞', '🤟', '🤘', '🤙', '👈',
        '👉', '👆', '🖕', '👇', '☝️', '👍', '👎', '✊', '👊', '🤛',
        '🤜', '👏', '🙌', '👐', '🤲', '🤝', '🙏', '✍️', '💪', '🦾',
        '🦿', '🦵', '🦶', '👂', '🦻', '👃', '🧠', '🫀', '🫁', '🦷',
        '🦴', '👀', '👁️', '👅', '👄', '💋', '🩸', '🦠', '💉', '💊'
    ];
    
    // 获取当前用户信息
    const getCurrentUser = () => {
        const userInfo = localStorage.getItem('userInfo');
        if (userInfo) {
            const parsed = JSON.parse(userInfo);
            return {
                _id: parsed.userId,
                username: parsed.username
            };
        }
        // 如果没有用户信息，使用默认值（仅用于测试）
        return {
            _id: '688cb2ff5e9bdf7c861dcd92',
            username: '张三'
        };
    };
    
    const currentUser = getCurrentUser();

    useEffect(() => {
        // 获取群聊信息
        fetchGroupInfo();
        // 获取群聊消息
        fetchGroupMessages();
        
        // 连接WebSocket
        const newSocket = io(`${http}${host}${port}`, {
            transports: ['websocket', 'polling'],
            reconnection: true,
            reconnectionAttempts: 5,
            reconnectionDelay: 1000
        });
        setSocket(newSocket);

        // 用户登录到WebSocket
        newSocket.emit('user_login', {
            userId: currentUser._id,
            username: currentUser.username
        });

        // 加入群聊房间
        newSocket.emit('join_group', {
            groupId: groupId,
            userId: currentUser._id
        });

        // 连接成功
        newSocket.on('connect', () => {
            console.log('群聊WebSocket连接成功');
        });

        // 连接错误
        newSocket.on('connect_error', (error) => {
            console.error('群聊WebSocket连接错误:', error);
        });

        // 接收群聊消息
        newSocket.on('receive_group_message', (message) => {
            console.log('收到群聊新消息:', message);
            setMessages(prev => {
                // 检查消息是否已经存在，避免重复添加
                const messageExists = prev.some(msg => msg._id === message._id);
                if (!messageExists) {
                    // 按时间顺序插入新消息
                    const newMessages = [...prev, message].sort((a, b) => 
                        new Date(a.time) - new Date(b.time)
                    );
                    return newMessages;
                }
                return prev;
            });
        });

        // 群聊消息发送确认
        newSocket.on('group_message_sent', (data) => {
            console.log('群聊消息发送确认:', data);
            if (data.success && data.data) {
                // 检查消息是否已经存在，避免重复添加
                setMessages(prev => {
                    const messageExists = prev.some(msg => msg._id === data.data._id);
                    if (!messageExists) {
                        // 按时间顺序插入新消息
                        const newMessages = [...prev, data.data].sort((a, b) => 
                            new Date(a.time) - new Date(b.time)
                        );
                        return newMessages;
                    }
                    return prev;
                });
            }
        });

        return () => {
            // 离开群聊房间
            newSocket.emit('leave_group', {
                groupId: groupId,
                userId: currentUser._id
            });
            newSocket.disconnect();
        };
    }, [groupId, currentUser._id, currentUser.username]);

    useEffect(() => {
        // 滚动到底部
        scrollToBottom();
    }, [messages]);

    // 点击外部关闭表情选择器和群聊菜单
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (showEmojiPicker && !event.target.closest(`.${styles.emojiPicker}`) && !event.target.closest(`.${styles.emojiButton}`)) {
                setShowEmojiPicker(false);
            }
            if (showGroupMenu && !event.target.closest(`.${styles.groupMenu}`) && !event.target.closest(`.${styles.menuButton}`)) {
                setShowGroupMenu(false);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, [showEmojiPicker, showGroupMenu]);

    const fetchGroupInfo = async () => {
        try {
            const response = await fetch(`${http}${host}${port}/groups/${groupId}`);
            const data = await response.json();
            
            console.log('群聊信息响应:', data);
            
            if (data.code === 200) {
                setGroupInfo(data.data);
            } else {
                setError(data.message || '获取群聊信息失败');
            }
        } catch (error) {
            console.error('获取群聊信息失败:', error);
            setError('获取群聊信息失败');
        }
    };

    const fetchGroupMessages = async () => {
        try {
            setLoading(true);
            const response = await fetch(`${http}${host}${port}/groupMessages/${groupId}?userId=${currentUser._id}`);
            const data = await response.json();
            
            console.log('群聊消息响应:', data);
            
            if (data.code === 200) {
                setMessages(data.data);
            } else {
                setError(data.message || '获取群聊消息失败');
            }
        } catch (error) {
            console.error('获取群聊消息失败:', error);
            setError('获取群聊消息失败');
        } finally {
            setLoading(false);
        }
    };

    // 获取可邀请的用户列表
    const fetchAvailableUsers = async () => {
        try {
            // 获取当前用户的学校ID
            const userInfo = localStorage.getItem('userInfo');
            let schoolId = null;
            
            if (userInfo) {
                const parsed = JSON.parse(userInfo);
                schoolId = parsed.schoolId;
            }
            
            // 构建请求URL，包含学校ID参数
            const url = schoolId 
                ? `${http}${host}${port}/users?schoolId=${schoolId}`
                : `${http}${host}${port}/users`;
                
            const response = await fetch(url);
            const data = await response.json();
            
            if (data.code === 200) {
                // 过滤掉已经在群聊中的用户
                const groupMemberIds = groupInfo.members.map(member => member._id);
                const availableUsers = data.data.filter(user => !groupMemberIds.includes(user._id));
                setAvailableUsers(availableUsers);
            }
        } catch (error) {
            console.error('获取用户列表失败:', error);
        }
    };

    const scrollToBottom = () => {
        messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
    };

    const handleSendMessage = async () => {
        if (!newMessage.trim() || !socket) return;

        const messageData = {
            groupId: groupId,
            from: currentUser._id,
            content: newMessage.trim(),
            messageType: 'text'
        };

        console.log('发送群聊消息:', messageData);

        // 发送WebSocket消息（WebSocket会负责保存到数据库）
        socket.emit('send_group_message', messageData);

        // 清空输入框
        setNewMessage('');
        
        // 添加发送状态提示
        console.log('群聊消息已发送，等待确认...');
    };

    const handleKeyPress = (e) => {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            handleSendMessage();
        }
    };

    // 切换表情选择器显示状态
    const toggleEmojiPicker = () => {
        setShowEmojiPicker(!showEmojiPicker);
    };

    // 切换群聊菜单显示状态
    const toggleGroupMenu = () => {
        setShowGroupMenu(!showGroupMenu);
    };

    // 选择表情
    const selectEmoji = (emoji) => {
        setNewMessage(prev => prev + emoji);
        setShowEmojiPicker(false);
        
        // 聚焦到输入框
        const textarea = document.querySelector(`.${styles.messageInput}`);
        if (textarea) {
            textarea.focus();
        }
    };

    // 邀请成员
    const handleInviteMembers = async () => {
        if (selectedUsers.length === 0) {
            alert('请选择要邀请的成员');
            return;
        }

        setIsLoading(true);
        try {
            const response = await fetch(`${http}${host}${port}/groups/addMembers`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    groupId: groupId,
                    memberIds: selectedUsers,
                    operatorId: currentUser._id
                }),
            });

            const data = await response.json();
            
            if (response.ok) {
                alert('邀请成员成功');
                setShowInviteModal(false);
                setSelectedUsers([]);
                fetchGroupInfo(); // 刷新群聊信息
            } else {
                alert(data.msg || '邀请成员失败');
            }
        } catch (error) {
            console.error('邀请成员失败:', error);
            alert('邀请成员失败');
        } finally {
            setIsLoading(false);
        }
    };

    // 移除成员
    const handleRemoveMember = async () => {
        if (!selectedRemoveUser) {
            alert('请选择要移除的成员');
            return;
        }

        setIsLoading(true);
        try {
            const response = await fetch(`${http}${host}${port}/groups/removeMember`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    groupId: groupId,
                    userId: selectedRemoveUser,
                    operatorId: currentUser._id
                }),
            });

            const data = await response.json();
            
            if (response.ok) {
                alert('移除成员成功');
                setShowRemoveModal(false);
                setSelectedRemoveUser('');
                fetchGroupInfo(); // 刷新群聊信息
            } else {
                alert(data.msg || '移除成员失败');
            }
        } catch (error) {
            console.error('移除成员失败:', error);
            alert('移除成员失败');
        } finally {
            setIsLoading(false);
        }
    };

    // 解散群聊
    const handleDissolveGroup = async () => {
        if (!confirm('确定要解散群聊吗？此操作不可撤销。')) {
            return;
        }

        setIsLoading(true);
        try {
            const response = await fetch(`${http}${host}${port}/groups/${groupId}`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    operatorId: currentUser._id
                }),
            });

            const data = await response.json();
            
            if (response.ok) {
                alert('群聊已解散');
                navigate('/layout/xiaoxi');
            } else {
                alert(data.msg || '解散群聊失败');
            }
        } catch (error) {
            console.error('解散群聊失败:', error);
            alert('解散群聊失败');
        } finally {
            setIsLoading(false);
        }
    };

    const formatTime = (timestamp) => {
        if (!timestamp) return '';
        const date = new Date(timestamp);
        return date.toLocaleTimeString('zh-CN', { 
            hour: '2-digit', 
            minute: '2-digit' 
        });
    };

    // 检查当前用户是否是群主
    const isGroupOwner = groupInfo?.createdBy?._id === currentUser._id;

    if (loading) {
        return (
            <div className={styles.loadingContainer}>
                <div className={styles.loadingText}>加载中...</div>
            </div>
        );
    }

    if (error) {
        return (
            <div className={styles.errorContainer}>
                <div className={styles.errorText}>{error}</div>
                <button 
                    className={styles.retryButton}
                    onClick={() => {
                        setError('');
                        fetchGroupInfo();
                        fetchGroupMessages();
                    }}
                >
                    重试
                </button>
            </div>
        );
    }

    return (
        <div className={styles.groupChatContainer}>
            {/* 群聊头部 */}
            <div className={styles.groupChatHeader}>
                <button 
                    className={styles.backButton}
                    onClick={() => navigate('/layout/xiaoxi')}
                >
                    ← 返回
                </button>
                <div className={styles.groupInfo}>
                    <div className={styles.groupAvatar}>
                        <div className={styles.defaultGroupAvatar}>
                            👥
                        </div>
                    </div>
                    <div className={styles.groupDetails}>
                        <div className={styles.groupName}>
                            {groupInfo?.name || '群聊'}
                        </div>
                        <div className={styles.groupMembers}>
                            {groupInfo?.members?.length || 0} 人
                        </div>
                    </div>
                </div>
                
                {/* 群聊菜单按钮 */}
                <div className={styles.menuContainer}>
                    <button 
                        className={styles.menuButton}
                        onClick={toggleGroupMenu}
                        title="群聊设置"
                    >
                        ⋯
                    </button>
                    
                    {/* 群聊菜单 */}
                    {showGroupMenu && (
                        <div className={styles.groupMenu}>
                            <button 
                                className={styles.menuItem}
                                onClick={() => {
                                    setShowInviteModal(true);
                                    fetchAvailableUsers();
                                    setShowGroupMenu(false);
                                }}
                            >
                                📨 邀请成员
                            </button>
                            {isGroupOwner && (
                                <>
                                    <button 
                                        className={styles.menuItem}
                                        onClick={() => {
                                            setShowRemoveModal(true);
                                            setShowGroupMenu(false);
                                        }}
                                    >
                                        👤 移除成员
                                    </button>
                                    <button 
                                        className={`${styles.menuItem} ${styles.dangerItem}`}
                                        onClick={() => {
                                            setShowGroupMenu(false);
                                            handleDissolveGroup();
                                        }}
                                    >
                                        🗑️ 解散群聊
                                    </button>
                                </>
                            )}
                        </div>
                    )}
                </div>
            </div>

            {/* 消息列表 */}
            <div className={styles.messagesContainer}>
                {messages.map((message, index) => {
                    const isSentByMe = message.from._id === currentUser._id;
                    
                    return (
                        <div 
                            key={message._id || index} 
                            className={`${styles.messageItem} ${
                                isSentByMe ? styles.sentMessage : styles.receivedMessage
                            }`}
                        >
                            <div className={styles.messageContent}>
                                {!isSentByMe && (
                                    <div className={styles.senderName}>
                                        {message.from.username || '未知用户'}
                                    </div>
                                )}
                                <div className={styles.messageText}>
                                    {message.content || '消息内容为空'}
                                </div>
                                <div className={styles.messageTime}>
                                    {formatTime(message.time)}
                                </div>
                            </div>
                        </div>
                    );
                })}
                <div ref={messagesEndRef} />
            </div>

            {/* 输入区域 */}
            <div className={styles.inputContainer}>
                <div className={styles.inputWrapper}>
                    <textarea
                        value={newMessage}
                        onChange={(e) => setNewMessage(e.target.value)}
                        onKeyPress={handleKeyPress}
                        placeholder="输入消息..."
                        className={styles.messageInput}
                        rows="1"
                    />
                    
                    {/* 表情按钮 */}
                    <button 
                        type="button"
                        className={styles.emojiButton}
                        onClick={toggleEmojiPicker}
                        title="表情"
                    >
                        😊
                    </button>
                    
                    {/* 表情选择器 */}
                    {showEmojiPicker && (
                        <div className={styles.emojiPicker}>
                            <div className={styles.emojiGrid}>
                                {emojis.map((emoji, index) => (
                                    <button
                                        key={index}
                                        className={styles.emojiItem}
                                        onClick={() => selectEmoji(emoji)}
                                        title={emoji}
                                    >
                                        {emoji}
                                    </button>
                                ))}
                            </div>
                        </div>
                    )}
                    
                    <button 
                        onClick={handleSendMessage}
                        className={styles.sendButton}
                        disabled={!newMessage.trim()}
                    >
                        发送
                    </button>
                </div>
            </div>

            {/* 邀请成员模态框 */}
            {showInviteModal && (
                <div className={styles.modalOverlay}>
                    <div className={styles.modal}>
                        <div className={styles.modalHeader}>
                            <h3>邀请成员</h3>
                            <button 
                                className={styles.closeButton}
                                onClick={() => {
                                    setShowInviteModal(false);
                                    setSelectedUsers([]);
                                }}
                            >
                                ×
                            </button>
                        </div>
                        <div className={styles.modalBody}>
                            <div className={styles.userList}>
                                {availableUsers.map(user => (
                                    <label key={user._id} className={styles.userItem}>
                                        <input
                                            type="checkbox"
                                            checked={selectedUsers.includes(user._id)}
                                            onChange={(e) => {
                                                if (e.target.checked) {
                                                    setSelectedUsers([...selectedUsers, user._id]);
                                                } else {
                                                    setSelectedUsers(selectedUsers.filter(id => id !== user._id));
                                                }
                                            }}
                                        />
                                        <span>{user.username}</span>
                                    </label>
                                ))}
                            </div>
                        </div>
                        <div className={styles.modalFooter}>
                            <button 
                                className={styles.cancelButton}
                                onClick={() => {
                                    setShowInviteModal(false);
                                    setSelectedUsers([]);
                                }}
                            >
                                取消
                            </button>
                            <button 
                                className={styles.confirmButton}
                                onClick={handleInviteMembers}
                                disabled={isLoading || selectedUsers.length === 0}
                            >
                                {isLoading ? '邀请中...' : '邀请'}
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* 移除成员模态框 */}
            {showRemoveModal && (
                <div className={styles.modalOverlay}>
                    <div className={styles.modal}>
                        <div className={styles.modalHeader}>
                            <h3>移除成员</h3>
                            <button 
                                className={styles.closeButton}
                                onClick={() => {
                                    setShowRemoveModal(false);
                                    setSelectedRemoveUser('');
                                }}
                            >
                                ×
                            </button>
                        </div>
                        <div className={styles.modalBody}>
                            <div className={styles.userList}>
                                {groupInfo?.members?.filter(member => member._id !== currentUser._id).map(member => (
                                    <label key={member._id} className={styles.userItem}>
                                        <input
                                            type="radio"
                                            name="removeUser"
                                            value={member._id}
                                            checked={selectedRemoveUser === member._id}
                                            onChange={(e) => setSelectedRemoveUser(e.target.value)}
                                        />
                                        <span>{member.username}</span>
                                    </label>
                                ))}
                            </div>
                        </div>
                        <div className={styles.modalFooter}>
                            <button 
                                className={styles.cancelButton}
                                onClick={() => {
                                    setShowRemoveModal(false);
                                    setSelectedRemoveUser('');
                                }}
                            >
                                取消
                            </button>
                            <button 
                                className={styles.confirmButton}
                                onClick={handleRemoveMember}
                                disabled={isLoading || !selectedRemoveUser}
                            >
                                {isLoading ? '移除中...' : '移除'}
                            </button>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
};

export default GroupChat; 